package com.alogic.xscript.plugins;

import com.alogic.load.Loader;
import com.alogic.textfilter.TextFilter;
import com.alogic.textfilter.TextFilterFactory;
import com.alogic.xscript.AbstractLogiclet;
import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsObject;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import org.apache.commons.lang3.StringUtils;

/**
 * 文本过滤器
 *
 * @since 1.6.13.10 [20200827 duanyy] <br>
 * - 增加filter插件 <br>
 */
public class Filter extends AbstractLogiclet {
    protected String $id;
    protected String $value;
    protected boolean raw = false;
    protected boolean ref = false;
    protected String $filter = "default";

    public Filter(String tag, Logiclet p) {
        super(tag, p);
    }

    @Override
    public void configure(Properties p){
        super.configure(p);

        $id = PropertiesConstants.getRaw(p,"id",$id);
        $value = PropertiesConstants.getRaw(p,"value",$value);
        $filter = PropertiesConstants.getRaw(p,"type",$filter);
        raw = PropertiesConstants.getBoolean(p,"raw",raw);
        ref = PropertiesConstants.getBoolean(p,"ref",ref);
    }

    @Override
    protected void onExecute(XsObject root, XsObject current, final LogicletContext ctx, final ExecuteWatcher watcher){
        String id = PropertiesConstants.transform(ctx,$id,"");
        if (StringUtils.isNotEmpty(id)) {
            String value = ref?
                    (raw?PropertiesConstants.getRaw(ctx,$value,""):PropertiesConstants.getString(ctx,$value,"",false)):
                    PropertiesConstants.transform(ctx,$value,"");
            if (StringUtils.isEmpty(value)){
                value = raw?PropertiesConstants.getRaw(ctx,id,""):PropertiesConstants.getString(ctx,id,"",false);
            }
            if (StringUtils.isNotEmpty(value)){
                String filterId = PropertiesConstants.transform(ctx,$filter,"default");
                Loader<TextFilter> loader = TextFilterFactory.getDefault();
                if (loader != null) {
                    TextFilter filter = loader.load(filterId, true);
                    if (filter != null) {
                        ctx.SetValue(id, filter.doFilter(value, ctx));
                    } else {
                        log(String.format("[%s]Text filter is not found:%s", this.getXmlTag(), filterId));
                    }
                }
            }
        }
    }
}
